package top.cmx.learn.thread.test;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author cmx
 */
public class LockCarStock {
    int cars;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    /**
     * 生产车
     */
    public void productCar() {
        lock.lock();
        try {
            if (cars < 20) {

                System.out.println("生产车……" + cars);
                cars++;
                //唤醒
                condition.signalAll();
            } else {
                condition.await();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    /**
     * 消费车
     */
    public void consumeCar() {
        lock.lock();
        try {
            if (cars > 0) {
                System.out.println("销售车……" + cars);
                cars--;
                //唤醒
                condition.signalAll();
            } else {
                condition.await();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }
}
